//门店列表数据
var storeManage = function() {
    var storeId = $('#store').find("option:selected").val();
    var tmp = '';

    var _init = function() {

        var table = $('#storeproduct_table');
        var tableUnit=table.dataTable({
            "processing": true,            
            serverSide: true,// 开启服务器模式
            "ajax": {
                url:storeList_url,
                data:{'storeId':storeId} 
            },
            "autoWidth": false,
            "columns": [
                {
                    "data": "id",
                    "render": function(data, type, row, meta) {
                        return '<div class="left product">'+
                                    '<img class="pic" src="'+row.imgUrl+'" alt="">'+
                                    '<img class="btn-del" src="/public/static/admin/pages/image/recycle.png" alt="">'+
                                    '<span class="span pName">'+row.title+'</span>'+
                                    '<span class="span Pprice">￥'+row.currentPrice/100+'</span>'+
                                    '<label class="btn btn-default checkbox-inline btn-recommand margin-bottom" ><input style="display:none" type="checkbox" value="'+row.recommendation+'" name="recommend" style="position: relative !important; padding: 0;margin: 0;">首页推荐</label>'+
                                '</div>';
                    }
                },
            ],
            "language": {
                "lengthMenu": "每页显示 _MENU_ 条记录",
                "emptyTable": "暂无数据记录",
                "info": "显示 _START_ 至 _END_ 条数据，共 _TOTAL_ 条记录！",
                "zeroRecords": "没有搜索到匹配记录",
                "infoEmpty": "",
                "infoFiltered": "",
                "processing": "数据加载中,请稍后..."
            },
            "pageLength": 12,
            "lengthMenu": [[12, 24, 36, 48, 60], [12, 24, 36, 48, 60]],
            "ordering": false, // 禁止排序
            "stateSave": true,
            "stateSaveParams": function (settings, data) {
                var search = data.search.search;
                if(search){
                    var arr = $.parseJSON(search);
                    for(var key in arr){
                        $("#searchForm input[name='"+key+"']").val(arr[key]);
                        $("#searchForm select[name='"+key+"']").val(arr[key]);
                    }
                }
            },
            "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'table_b relative'<'col-md-5'i><'col-md-7'>lp>",
            "fnCreatedRow": function(nRow, aData, iDataIndex){
                tmp = tmp + aData['productId'] + ',';
                $("input[name='tagProduct']").val(tmp);
                if(aData['recommendation'] == 1){  //显示为首页推荐
                    $(nRow).find('input').prop('checked',true);
                    $(nRow).find('.product label').attr('style','color:red');
                    // console.log();
                }
            },
            "fnInitComplete": function() {
            },           
        });

        // 添加积分商品
        $('#btn_new_role').click(function(event) {            
            $('#storeproduct').modal('show');
            //product_table.DataTable().ajax.reload();
            product_table.DataTable().draw(false);
        });

        // 删除积分商品
        table.on('click', '.btn-del', function(event) {
            var oData_arr = table.DataTable().rows($(this).parents("tr")).data(); // 操作行对象
            var _id = oData_arr[0].id;

            var text = $(this).data('confirm') ? $(this).data('confirm') : '确定要删除？';
            var title = $(this).data('title') ? $(this).data('title') : '删除积分兑换商品';
            var confirmBtn = $(this).data('confirmbtn') ? $(this).data('confirmbtn') : '确定';
            var cancelBtn = $(this).data('cancelbtn') ? $(this).data('cancelbtn') : '取消';
            layer.confirm(
                text, // 内容
                {
                    // icon: 7,
                    // 标题
                    title: title,
                    // 按钮
                    btn: [confirmBtn, cancelBtn]
                },
                function(index){
                    $.ajax({
                        url : groupDel_url,
                        type : 'delete',
                        dataType : 'json',
                        contentType: "application/json; charset=utf-8",
                        data : JSON.stringify({ id:_id}),
                        async: false
                    }).done(function(data) {
                        if (data.code === '1') {
                            layer.msg('删除成功');
                            window.location.reload();  //重新加载以更新tagProduct值

                        } else if (data.code === '2') {
                            layer.msg(data.message);
                        }
                    });
                    layer.close(index);
                }
            );
            
        });       
        
        // 积分商品-首页推荐
        table.on('click', '.btn-recommand', function(event) {
            if ($(event.target).is("input"))  //阻止input框再次执行
                return;
            
            var oData_arr = table.DataTable().rows($(this).parents("tr")).data(); // 操作行对象
            var _id = oData_arr[0].id;  //积分ID
            var recommendation = $(this).find('input').is(':checked') ? 2 : 1;
            $.ajax({
                url :recommend_url,
                type : 'POST',
                dataType : 'json',
                contentType:"application/json; charset=utf-8",
                data : JSON.stringify({'id':_id,'recommendation':recommendation}),
            }).done(function(data) {
                if(data.code === '2') {
                    layer.msg(data.message);
                    //table.DataTable().ajax.reload();
                    table.DataTable().draw(false);
                } else{
                    //table.DataTable().ajax.reload();
                    table.DataTable().draw(false);
                }
            });
        });

        //门店商品数据
        var product_table = $('#product_table');
        product_table.dataTable({
            "processing": true,
            serverSide: false,
            destroy:true, //Cannot reinitialise DataTable,解决重新加载表格内容问题
            "ajax": {
                url:layer_product,
                data:{'storeId':storeId}// 列表查询
            },
            "autoWidth": false,
            "columns": [
                {
                    "data": "title",
                     "render": function(data, type, row, meta) {
                        return '<div class="left product">'+
                                    '<input type="checkbox" name="selectId" value="'+row.id+'" style="display:none" />'+
                                    '<img class="pic" src="'+row.imgUrl+'" alt="">'+
                                    '<span class="span pName">'+row.title+'</span>'+
                                    '<span class="span Pprice">￥'+row.currentPrice/100+'</span>'+
                                '</div>'+
                                '<div class="left selected" style="display:none">已选'+
                                '</div>';
                    }
                },
                {
                    "data": "typeId",
                    "render": function(data, type, row, meta) {
                        return ','+data+',';
                    },
                    "visible": false,
                }
            ],
            "language": {
                url: '/public/static/assets/pages/Chinese.json'
            },
            "pageLength": 8,
            "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'table_b relative'<'col-md-5'i><'col-md-7'>p>",
            "fnCreatedRow": function(nRow, aData, iDataIndex){
                var tagProduct = $("#groupProduct input[name='tagProduct']").val();
                if(tagProduct.indexOf(aData['id']+',') >= 0) {  //标识已选中商品
                    $(nRow).find('div.selected').attr('style','display:block');
                    $(nRow).find("input[name='selectId']").prop("checked", true);
                }
            },
            "fnInitComplete": function() {}
        });

        //选择商品
        product_table.on('click', '.sorting_1', function(event) {
            var oData_arr = product_table.DataTable().rows($(this).parents("tr")).data(); // 操作行对象
            var product_id = oData_arr[0].id;   //商品ID
            $(this).find("div.selected").toggle();
            var $item =  $(this).find("div.selected");
            if ($(this).find("div.selected").is(':visible')) {  //选中,添加
                //添加前检测是否设置积分价格
                $.ajax({
                    url : checkPrice,
                    type : 'delete',
                    dataType : 'json',
                    contentType:"application/json; charset=utf-8",
                    data : JSON.stringify({ product_id:product_id}),
                    async: false
                }).done(function(data) {
                    if (data.code === '1') {
                        $item.prev().find("input[name='selectId']").prop("checked", true);
                    } else if (data.code === '2') {
                        $item.hide();
                        layer.msg(data.message);
                    }
                });
                
            } else {  //删除前需检查是否有未完成订单
                $.ajax({
                    url : checkOrder_url,
                    type : 'delete',
                    dataType : 'json',
                    contentType:"application/json; charset=utf-8",
                    data : JSON.stringify({ storeId:storeId,product_id:product_id}),
                    async: false
                }).done(function(data) {
                    if (data.code === '1') {
                        $item.prev().find("input[name='selectId']").prop("checked", false);
                    } else if (data.code === '2') {
                        $item.show();
                        layer.msg(data.message);
                    }
                });
            }
        });

        //选择商品-确认
        $('#storeproduct .btn-confrom-product').click(function(){
            var _data = product_table.$("input").serializeObject();
            var param = {'selectId':JSON.stringify(_data),'store_id':storeId};
            $.ajax({
                url: selectPost_url,
                type: 'POST',
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(param),
            }).done(function (data) {
                if (data.status === '1') {// 正确
                    $("input[name='tagProduct']").val('');
                    window.location.reload();  //重新加载以更新tagProduct值
                    // table.DataTable().ajax.reload();
                } else if (data.status === '2') {// 错误
                    layer.msg(data.msg); // 返回错误信息
                }
            })
            // $('.modal').hide();
        });
    };

    return {
        init: function() {
            _init();
        }
    };

}();


$('#search .form-control').change(function(event){  //积分商品排序展示
    var order =   $("#search select[name='search']").val();
    var param={"order":order};
    $('#storeproduct_table').DataTable().search(JSON.stringify(param)).draw();
});

$('#search2 .form-control').change(function(event){  //门店商品分类搜索
    var typeId =   ','+$("#search2 select[name='typeId']").val()+',';
    if(typeId.length == 2) {  //搜索所有商品
        typeId = '';
    }
    $('#product_table').DataTable().columns(1).search(typeId,false,false).draw();//对第二列进行精确非智能搜索
});

$(function() {
    storeManage.init();
});